import sys
import _thread
import time
import http.client
import hashlib
import urllib
import random
import json
import pyperclip
import tkinter
from pip._vendor.distlib.compat import raw_input
from tkinter import END,INSERT
from PIL import ImageTk,Image # pip install pillow ; PIL 只支持 python2 ,python3 工程师写了 pillow 兼容 PIL
import pyautogui as pag


t = tkinter.Tk()
save = "save\n"
save_status = False
toLang = 'zh'           # 译文语种

############################### 窗口退出函数 #################################
def quit():
	t.destroy()
##############################################################################

############################### 文本复制函数 #################################
def paste_text():
	global save_status
	save_status = True
##############################################################################

############################### 窗口移动函数 #################################
	
def win_move(event):
	global dst_x,dst_y
	dst_x += event.x
	dst_y += event.y
	if (dst_x > t.winfo_screenwidth() - 360 ):
		dst_x = t.winfo_screenwidth() - 360
	if (dst_y > t.winfo_screenheight() - 180) :
		dst_y = t.winfo_screenheight() - 180
	if (dst_x < 0 ):
		dst_x = 0
	if (dst_y < 0) :
		dst_y = 0
	t.geometry("%dx%d+%d+%d" % (width,height,dst_x ,dst_y ))
	#print(event.x,event.y)
##############################################################################

############################### 语言选择函数 #################################
def Language_sel():
	global toLang
	if ( toLang == 'zh' ):
		toLang = 'en'
		lg['text'] = '英文'
	else:
		toLang = 'zh'
		lg['text'] = '中文'
	t.update()

##############################################################################


#################################### 打印函数 ##################################
def print_tk(ptext,tkstr):
	ptext.delete(1.0,tkinter.END)
	ptext.insert(INSERT,tkstr)
################################################################################

################################## 百度翻译接口 ################################
appid = ''        # 填写你的appid
secretKey = ''    # 填写你的密钥
 
httpClient = None
myurl = '/api/trans/vip/translate'  # 通用翻译API HTTP地址
 
fromLang = 'auto'       # 原文语种
salt = random.randint(32768, 65536)
# 录入剪切面板内容
q = pyperclip.paste()
def translate_fun() :
	global save
	global q
	try:
		sign = appid + q + str(salt) + secretKey
		sign = hashlib.md5(sign.encode()).hexdigest()
		tmyurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(q) + '&from=' + fromLang + \
        		'&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign
		httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
		httpClient.request('GET', tmyurl)
		# response是HTTPResponse对象
		response = httpClient.getresponse()
		result_all = response.read().decode("utf-8")
		result = json.loads(result_all)
		save = result['trans_result'][0]['dst']
		print_tk(text,save)
	except Exception as e:
		print(e)
		text.insert(INSERT,'网络超时，重试...')
		time.sleep(1)
		q = "err"
		if httpClient:
    			httpClient.close()

		#translate_fun()

################################################################################


################################### 翻译进程 ###################################
def translate(delay):
	global text
	global save_status
	global q
	while 1 :
		time.sleep(delay)
		if save_status :
			save_status = False
			pyperclip.copy(save)
			continue
		tq = pyperclip.paste()
		if ( q == tq or len(tq) == 0 ):
			continue
		q = tq
		print_tk(text,'等待翻译...\n')
		translate_fun()

################################################################################

#窗口初始化
image2 =Image.open(r'D:\python_code\translate\bg.jpg')
background_image = ImageTk.PhotoImage(image2)
t.title("Dtrans")
width = background_image.width()
height = background_image.height()
dst_x = t.winfo_screenwidth() - 360
dst_y = t.winfo_screenheight() - 180 - t.winfo_screenheight() / 24
t.geometry("%dx%d+%d+%d" % (width,height,dst_x,dst_y))

canvas_t = tkinter.Canvas(t,width=width,height=height)
canvas_t.create_image(width / 2,height / 2,image=background_image)
canvas_t.pack()	
v = tkinter.Button( t,text = "退出",command = quit)
v.place(relx=0.925,rely=0.9,anchor="center")
paste = tkinter.Button( t,text = "复制",command = paste_text)
paste.place(relx=0.925,rely=0.1,anchor="center")
move = tkinter.Button( t,text = "移动")
move.bind('<ButtonRelease-1>',win_move)
move.place(relx=0.925,rely=0.5,anchor="center")
t.configure(bg='gray')
lg = tkinter.Button( t,text = "中文",command = Language_sel)
lg.place(relx=0.925,rely=0.3,anchor="center")

t.overrideredirect(True) #去掉边框,必须在 visibility 之前
t.wait_visibility(t) #这是兼容linux的方法
t.wm_attributes('-topmost', True) #窗口置顶
t.wm_attributes('-alpha', 0.7) #窗口透明
text = tkinter.Text(t,width=30,height=13)# height是行,width是字节宽度
text.place(relx=0.5,rely=0.5,anchor="center")
text.insert(INSERT,'欢迎使用\n')
text.insert(INSERT,'源码: https://gitee.com/Blg-daijh/py-translate?_from=gitee_search\n')
text.insert(INSERT,'作者: 板蓝根 Blg-daijh\n')

_thread.start_new_thread( translate,(0.5,)  )
t.mainloop()

if httpClient:
    	httpClient.close()

